<template>
  <el-radio-group v-model="curValue" :disabled="disabled" v-bind="$attrs" v-on="$listeners">
    <el-radio v-for="(v,i) in comOptList" :key="i" :value="v.dictCode" :label="v.dictCode">{{ v.dictName }}</el-radio>
  </el-radio-group>
</template>
<script>
import { SLMDict } from '@/api/dataDict'
export default {
  name: 'CDictRadio',
  inheritAttrs: false,
  props: {
    dictTypeCode: {
      type: String,
      default: ''
    },
    value: {
      type: [String, Number],
      default: ''
    },
    label: {
      type: [String, Number],
      default: ''
    },
    disabled: {
      type: Boolean,
      default: false
    },
    include: {
      type: [Array, String],
      default: () => []
    },
    exclude: {
      type: [Array, String],
      default: () => []
    }
  },
  data() {
    return {
      optList: [],
      curValue: ''
    }
  },
  computed: {
    comInclude() {
      if (typeof this.include === 'string') {
        return this.include.split(',').filter(e => e !== '')
      }
      return this.include.filter(e => e !== '')
    },
    comExclude() {
      if (typeof this.exclude === 'string') {
        return this.exclude.split(',').filter(e => e !== '')
      }
      return this.exclude.filter(e => e !== '')
    },
    comOptList() {
      return this.optList.filter(e => {
        const i = this.comInclude
        const ee = this.comExclude
        return (i.length === 0 || (i.length > 0 && i.includes(e.dictCode))) && (ee.length === 0 || (ee.length > 0 && !ee.includes(e.dictCode)))
      })
    }
  },
  watch: {
    value: {
      handler(n) {
        this.curValue = /^\d+$/.test(n) ? n.toString() : n
      },
      immediate: true
    },
    curValue(n) {
      this.$emit('input', n)
      this.updateLabel(n)
    }
  },
  created() {
    this.getDataDict()
  },
  methods: {
    getDataDict() {
      SLMDict(this.dictTypeCode).then(res => {
        this.optList = res.data
      })
    },
    updateLabel(v) {
      let label = ''
      for (const item of this.comOptList) {
        if (v === item.dictCode) {
          label = item.dictName
        }
      }
      this.$emit('update:label', label)
    }
  }
}
</script>
